import { normalizeClass } from "@vue/shared";
import { defineComponent, PropType, watch, reactive, mergeProps, getCurrentInstance } from "vue";
import { getComponent } from '../_util/props-util';
import Trigger from '../trigger'
import placements from './placements'
import tooltipProps from './tooltipProps'

export default defineComponent({
  name: 'x-tooltip',
  props: tooltipProps,
  slots: ['title'],
  emits: ['update:visible', 'visibleChange'],
  setup(props, { emit, slots }) {
    const { proxy: vm } = getCurrentInstance()
    const { prefixCls, builtinPlacements } = props
    const state = reactive({
      visible: props.visible
    })
    watch(() => props.visible, v => {
      state.visible = v
    })

    function onPopupVisibleChange(v: boolean) {
      state.visible = v
      emit('update:visible', v)
      emit('visibleChange', v)
    }

    function getPopupElement() {
      return getComponent(vm, 'title')
    }

    return () => {
      const popupClass = normalizeClass([
        `${prefixCls} ${prefixCls}-placement-${props.placement}`,
        props.popupClass
      ])
      
      const triggerProps = {
        action: props.trigger,
        disabled: props.disabled,
        popup: getPopupElement(),
        popupClass,
        popupTransitionName:  props.transitionName || prefixCls,
        popupAlign: props.align || builtinPlacements?.[props.placement] || placements[props.placement],
        getPopupContainer: props.getPopupContainer,
        onPopupVisibleChange,
        mouseEnterDelay: props.mouseEnterDelay,
        mouseLeaveDelay: props.mouseLeaveDelay,
        popupStyle: props.popupStyle,
      }
      return (
        <Trigger {...triggerProps}>
          {slots.default?.()}
        </Trigger>
      )
    }
  }
})